﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Orchard;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Mvc.Html;
using Orchard.Utility.Extensions;


namespace Contrib.ProjectionCarousel.Providers.Layouts {
    public class LayoutShapes : IDependency {
        public LayoutShapes() {
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        [Shape]
        public void Carousel(dynamic Display, TextWriter Output, HtmlHelper Html, string Id, IEnumerable<dynamic> Items, 
                            IEnumerable<string> OuterClasses, IDictionary<string, string> OuterAttributes,
                            IEnumerable<string> InnerClasses, IDictionary<string, string> InnerAttributes, 
                            IEnumerable<string> FirstItemClasses, IDictionary<string, string> FirstItemAttributes, IEnumerable<string> ItemClasses,  IDictionary<string, string> ItemAttributes ) 
        {            
            if (Items == null) return;

            var items = Items.ToList();
            var itemsCount = items.Count;

            if (itemsCount < 1) return;

            var outerDivTag = GetTagBuilder("div", Id, OuterClasses ?? new[] { "carousel slide" }, OuterAttributes);
            var innerDivTag = GetTagBuilder("div", string.Empty, InnerClasses ?? new[] { "carousel-inner" }, InnerAttributes);
            
            Output.Write(outerDivTag.ToString(TagRenderMode.StartTag));
            Output.Write(innerDivTag.ToString(TagRenderMode.StartTag));
            
            foreach (var item in items)
            {
                Output.Write(Display(item));
            }
            
            Output.Write(innerDivTag.ToString(TagRenderMode.EndTag));

            Output.Write("<a href=\"#{0}\" class=\"carousel-control left\" data-slide=\"prev\">&lsaquo;</a>",Id);
            Output.Write("<a href=\"#{0}\" class=\"carousel-control right\" data-slide=\"next\">&rsaquo;</a>",Id);

            Output.Write(outerDivTag.ToString(TagRenderMode.EndTag));

            Output.Write("<script>$(function () {$('"+ Id +"').carousel();}); </script>");

        }

        static TagBuilder GetTagBuilder(string tagName, string id, IEnumerable<string> classes, IDictionary<string, string> attributes)
        {
            var tagBuilder = new TagBuilder(tagName);
            if ( attributes != null )
                tagBuilder.MergeAttributes(attributes, false);
            foreach (var cssClass in classes ?? Enumerable.Empty<string>())
                tagBuilder.AddCssClass(cssClass);
            if (!string.IsNullOrWhiteSpace(id))
                tagBuilder.GenerateId(id);
            return tagBuilder;
        }

    }
}
